package com.etlmaster.executor.steps.extract;

import java.sql.Connection;
import java.sql.Statement;

import javax.sql.DataSource;

import com.etlmaster.core.BeanFactory;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;

/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("extractHive")
public class HiveExtractStep extends Step {

	private HiveExtractStepMeta meta;

	public HiveExtractStep(StepMeta meta) {
		super(meta);
		this.meta = (HiveExtractStepMeta) meta;
		// TODO Auto-generated constructor stub
	}

	
	@Override
	protected int handle() {
		int flag = StepState.RUNNING_FAILED;
		try {
			/*
			 * 目前只提供hive导出到本地或者HDFS路径 可配置解压，分隔符
			 */
			JdbcTemplate jdbcTemplate = new JdbcTemplate(
					(DataSource) BeanFactory.getBean(meta.getDsName()));

			Connection conn = jdbcTemplate.getDataSource().getConnection();
			Statement stmt = conn.createStatement();
			if (meta.isCompression()) {
				stmt.execute("set hive.exec.compress.output= false");
				meta.log("INFO","设置文件解压缩");
			}

			String delimiter = meta.getDelimiter();
			StringBuffer delimiterString = new StringBuffer("");

			if (delimiter != null && delimiter.length() != 0
					&& !"undefined".equalsIgnoreCase(delimiter)) {
				delimiterString.append("");
				meta.log("INFO","设置文件分隔符{}", delimiter);
			}

			String sql = "insert overwrite "
					+ (meta.isLocalPath() ? "local " : "") + "directory '"
					+ meta.getFilePath() + "' " + delimiterString
					+ meta.getSql() + "";
			meta.log("INFO","执行语句 ：{}，请等待...", sql);

			stmt.execute(sql);

			meta.log("INFO","sql：{}导入{}路径{}成功！", meta.getSql(),
					(meta.isLocalPath() ? "本地 " : "HDFS"), meta.getFilePath());
			return StepState.RUNNING_SUCCESSED;
		} catch (Exception e) {
			e.printStackTrace();
			return flag;
			// TODO: handle exception
		}
		// TODO Auto-generated method stub
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
}
